package com.item.Interceptor;

import com.item.POJO.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserInterceptor implements HandlerInterceptor
{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

       //获取请求的URL
        String url = request.getRequestURI();
        if (url.indexOf("/login.action") >=0){
            return  true;
        }
        //获取session
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("USER_SESSION");
        //判断Session中是否有用户数据，如果有，继续执行
        if (user!=null){
            return true;
        }
        //不符合条件的转发到登录页面
        request.setAttribute("msg","你还没用登录，请先登录！");
        request.getRequestDispatcher("/WEB-INF/JSP/login.jsp").forward(request,response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
